iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0

GenServer 訊息分成兩種:

  • Cast:單純送出,不在乎對象結果
  • Call:送出後開始等回應

在 GenServer 裡,使用 handle_call/2 來接收 Call,與 handle_cast/2 來收 Cast

cast

使用 handle_cast/2 callback 來處理新的 cast event

defmodule Bank do
  use GenServer
  
  def init(init_balance) do
    IO.puts "開戶存了 #{init_balance} 元。"
    {:ok, init_balance}
  end

  def handle_cast({:add, n}, balance) do
    new_state = balance + n
    IO.puts "存入 #{balance} 元。"
    
    {:noreply, new_state}
  end
end

接著使用 GenServer.cast/2 來呼叫他

iex(2)> {:ok, pid} = GenServer.start_link(Bank, 3000)
開戶存了 3000 元。
{:ok, #PID<0.114.0>}
iex(3)> GenServer.cast(pid, {:add, 400})
存入 3000 元。
:ok

上一篇
09 GenServer
下一篇
11 GenServer call
系列文
Elixir 多工 : Processes 與 OTP14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言